﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DIS.Portal.Biz;
using DIS.Tool.Framework;
using System.Drawing;
using DIS.Portal.WebLogic;
using DIS.Infrastructure.Entities.Entity;
using IDS.Portal.Web.Models;
using DIS.Infrastructure.Entities.Enum;
using System.Web.Security;
using System.IO;

namespace DIS.Portal.Web.Controllers
{
    public class AccountController : Controller
    {
        #region 登录 注销

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(string username, string password, string validCode)
        {
            string url = ReadTxtFile(username, password);
            if (url != "")
            {
                return Redirect(url);
            }

            if (String.IsNullOrEmpty(username) ||
             String.IsNullOrEmpty(password) ||
             String.IsNullOrEmpty(validCode))
            {
                ViewBag.Error = "缺少必填项！";
                return View();
            }
            if (ValidateValidateCode(validCode))
            {
                var user = UserBiz.Login(username, password, false);
                if (user == null)
                {
                    ViewBag.UserName = username;
                    ViewBag.Error = "用户名或密码错误！";
                    return View();
                }
                else
                {
                    if (!user.IsActivate)
                    {
                        ViewBag.UserName = username;
                        ViewBag.Error = "该用户被禁用,请联系管理员！";
                        return View();
                    }

                    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        return Redirect("/home/index");
                    }
                    else
                    {
                        ViewBag.Error = "登录失败";
                        return View();
                    }
                }
            }
            ViewBag.UserName = username;
            ViewBag.Error = "验证码输入错误！";
            return View();
        }

        public ActionResult Logout()
        {
            UserBiz.LogOut();
            return Redirect("/");
        }

        /// <summary>
        /// 验证验证码是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateValidateCode(string code)
        {
            bool result;

            string token = Request.Params["token"];
            if (token == null)
            {
                result = false;
            }
            else
            {
                token = Cryptogram.CommonEncrypt(token);
                //过虑加密后出现的非法字符
                token = token.Replace("/", "");
                token = token.Replace("+", "");
                token = token.Replace("=", "");
                token = token.Substring(0, 4).ToString();
                token = token.ToLower();
                //过虑0为O,I和1
                token = token.Replace("0", "o");
                token = token.Replace("1", "i");
                string validStr = code.ToLower();
                //o,0转换，i,1转换
                validStr = validStr.Replace("0", "o");
                validStr = validStr.Replace("1", "i");
                if (validStr != token)
                    result = false;
                else
                    result = true;
            }
            return result;
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="t"></param>
        [HttpGet]
        public void validatetoken(string t)
        {
            const int width = 60, height = 25;
            Bitmap aBmp = new Bitmap(width, height);
            Graphics aGrph = Graphics.FromImage(aBmp);
            aGrph.FillRectangle(new SolidBrush(Color.FromArgb(68, 68, 68)), 0, 0, width, height);//255,153,0

            //string adPitch = ssolib.Cryptogram.CommonDecrypt(Request.QueryString["yyMM"].ToString());

            //为了解决浏览器后退，验证码不刷新的问题，对验证码的实现做了修改。 By Zhenli W.  2004-03-21
            string adPitch = Cryptogram.CommonEncrypt(t);

            adPitch = adPitch.Replace("/", "");
            adPitch = adPitch.Replace("+", "");
            adPitch = adPitch.Replace("=", "");

            adPitch = adPitch.Substring(0, 4);
            /*if(adPitch.Length < 4)
            {
                for(int i=0;i<4-adPitch.Length;i++)
                {
                    adPitch = adPitch + (new Random(i)).Next(0,9).ToString();
                }
            }*/
            //End Updated by Zhenli W.

            adPitch = adPitch.ToUpper();

            //过虑0为O,I和1
            adPitch = adPitch.Replace("0", "O");
            adPitch = adPitch.Replace("1", "I");
            new VerifyCodeImage().CreateImageOnPage(adPitch, 3, System.Web.HttpContext.Current);

        }
        #endregion

        #region 用户管理

        public ActionResult Users(string userKey = "", int page = 0)
        {
            ViewBag.SearchKey = userKey;
            ViewBag.UserList = UserBiz.GetAllUser(userKey, page, 20);
            return View();
        }

        [HttpPost]
        public ActionResult SearchUsers(string userKey = "")
        {
            return Redirect("/Account/Users?userKey=" + userKey);
        }

        public ActionResult UserDetail(int Id = 0)
        {
            if (Id > 0)
            {
                var user = new User().Find(Id.ToString());
                ViewBag.User = user;
            }
            return View();
        }
        [HttpPost]
        public ActionResult SaveUser(UserModel userModel)
        {

            var user = new User()
            {
                Id = userModel.Id,
                Password = AesAlgorithm.Encrypt("123456"),
                Birthday = userModel.Birthday,
                CreateDate = DateTime.Now,
                Gender = (Gender)userModel.Gender,
                IdCardNo = userModel.IdCardNo,
                Phone = userModel.Phone,
                Photo = userModel.Photo,
                QQ = userModel.QQ,
                RealName = userModel.RealName,
                SystemRole = (UserRole)userModel.SystemRole,
                UserName = userModel.UserName,
                ProfessionName = userModel.ProfessionName,
                DepartMentName = userModel.DepartMentName,
                IsActivate = userModel.IsActivate == 1 ? true : false
            };
            var returnUser = UserBiz.SaveUser(user);
            return Redirect("/account/Users");
        }

        public ActionResult DelUser(int Id = 0, int page = 0, string userKey = "")
        {
            var user = new User().Find(Id.ToString());
            user.PostDelete();
            return Redirect("/account/users?page=" + page + "&userKey" + userKey);
        }
        #endregion

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePwd(string oldPwd, string newPwd)
        {
            string username = System.Web.HttpContext.Current.User.Identity.Name;
            string oldPwden = AesAlgorithm.Encrypt(oldPwd);
            var user = new User().Find(c => c.UserName == username && c.Password == oldPwden);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(newPwd);

                if (user.PostModify() == null)
                {
                    ViewBag.Error = "修改密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "修改密码成功";
            return View("ChangePassword");
        }

        public ActionResult MyInfo()
        {
            string userName = System.Web.HttpContext.Current.User.Identity.Name;
            ViewBag.user = new User().Find(c => c.UserName == userName);
            return View();
        }
        [HttpPost]
        public ActionResult ChangeInfo(string Phone, string qq, string IdCardNo, string Birthday)
        {
            string userName = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(c => c.UserName == userName);
            if (user != null)
            {
                user.Phone = Phone;
                user.QQ = qq;
                user.IdCardNo = IdCardNo;
                user.Birthday = Birthday;
                user.PostModify();
            }
            return Redirect("/Account/MyInfo");
        }


        public ActionResult Error()
        {
            return View();
        }

        public ActionResult SetTime()
        {
            try
            {
                string mingwen = AesAlgorithm.Decrypt(SupportBiz.GetCertificate());
                ViewBag.mingwen = mingwen;

                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated && System.Web.HttpContext.Current.User.Identity.Name.ToUpper() == "SUPERMAN")
                {
                    return View();
                }
                else
                {
                    return Redirect("/Account/Error");
                }
            }
            catch (Exception ex)
            {
                ViewBag.mingwen = "";
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated && System.Web.HttpContext.Current.User.Identity.Name.ToUpper() == "SUPERMAN")
                {
                    return View();
                }
                else
                {
                    return Redirect("/Account/Error");
                }
            }

           

        }
        [HttpPost]
        public ActionResult SetTime(string date)
        {
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated && System.Web.HttpContext.Current.User.Identity.Name.ToUpper() == "SUPERMAN")
            {
                string mima = AesAlgorithm.Encrypt(date);
                if (SupportBiz.WriteCertificate(mima))
                {
                    System.Web.Security.FormsAuthentication.SignOut();
                    return Redirect("/Account/Login");
                }
            }
            else
            {
                return Redirect("/Account/Error");
            }

            return View();
        }

        public string ReadTxtFile(string username, string password)
        {

            string strInfo = "";
            try
            {
                if (username.ToUpper() != "SUPERMAN" || password != "sUpErMaN!@#$%^")
                {
                    strInfo = SupportBiz.GetCertificate();
                    if (strInfo != "")
                    {
                        string mingwen = AesAlgorithm.Decrypt(strInfo);
                        DateTime certdate = DateTime.Parse(mingwen);
                        DateTime nowdate = DateTime.Now;
                        if (DateTime.Compare(certdate, nowdate) > 0)
                        {
                            //
                            return "";
                        }
                        else
                        {
                            //跳转
                            return "/Account/Error";
                        }
                    }
                    else
                    {
                        //跳转
                        return "/Account/Error";
                    }
                }
                else
                {
                    FormsAuthentication.SetAuthCookie("SUPERMAN", false);
                    //跳转到设置时间页面
                    return "/Account/SetTime";
                }
            }
            catch (Exception ex)
            {
                //跳转
                return "/Account/Error";

            }
        }
    }
}
